package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Resource
    private AdUserMapper adUserMapper;

    @Override
    public ResponseResult userLogin(AdUserDto dto) {

        //判断用户名或密码是否为空
        if (StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }
        //根据用户名查询用户信息
        Wrapper wrapper=new QueryWrapper();
        ((QueryWrapper)wrapper).eq("name",dto.getName());
        AdUser one = getOne(wrapper);
        //判断one是否为空
        if (one!=null){
            //判断用户的密码
            //根据用户输入的密码+数据库中盐进行加密，跟数据库中的password进行比较
            String hex = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
            System.out.println(hex);
            if (hex.equals(one.getPassword())){ //密码正确
                //生成token响应客户端
                Map<String, Object> map = new HashMap<>();
                map.put("password","");
                map.put("salt","");
                map.put("token", AppJwtUtil.getToken(one.getId().longValue()));
                map.put("user",one);
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
    }
}
